<template>
  <l-layout class="l-page-panel">
    <!-- <template #left> </template>
    <template #right> </template>
    <template #top> </template>
    <template #bottom> </template> -->

    <div class="api-bind-item">
      <div class="api-title" style="padding-left: 20px; margin-bottom: 20px">
        <label style="padding-right: 12px"> 设置关键主键 </label>
        <el-select v-model="primary" size="mini" placeholder="请选择" style="margin-right: 8px">
          <el-option v-for="item in columns" :key="item" :label="item" :value="item"> </el-option>
        </el-select>
      </div>

      <div class="api-title" style="padding-left: 20px; margin-bottom: 20px">
        <span class="name" style="padding-right: 12px">输出接口</span>
        <el-button size="mini" @click="restSaveParams">重置输出接口</el-button>
      </div>
      <div class="api-title" style="padding-left: 20px; margin-bottom: 20px">
        <label style="padding-right: 12px"> 参数模式 </label>
        <el-radio-group v-model="radioParam" @change="radioParamChange">
          <el-radio :label="2">数据结构模式</el-radio>
          <el-radio :label="1">请求参数模式</el-radio>
        </el-radio-group>
      </div>
      <div style="padding: 20px">
        <l-table
          style="overflow-y: auto; height: 600px"
          ref="mainTable"
          default-expand-all
          :columns="tableColumns"
          :dataSource="outData"
          row-key="id"
          :isPage="false"
        >
          <template v-slot:type="scope">
            {{ getOutName(scope.row) }}
          </template>
          <template v-slot:setting="scope">
            <div v-if="scope.row.parent">
              <el-select v-model="scope.row.value" size="mini" placeholder="请选择" clearable>
                <el-option
                  v-for="options in getChildFormOptions(scope.row)"
                  :key="options.value"
                  :label="options.label"
                  :value="options.value"
                >
                </el-option>
              </el-select>
            </div>
            <div v-else>
              <el-select
                v-if="scope.row.type == 'basic'"
                v-model="scope.row.value"
                size="mini"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="options in mainFormOptions"
                  :key="options.value"
                  :label="options.label"
                  :value="options.value"
                >
                </el-option>
              </el-select>
              <el-select
                v-if="scope.row.type == 'array'"
                v-model="scope.row.value"
                size="mini"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="options in arrFormOptions"
                  :key="options.value"
                  :label="options.label"
                  :value="options.value"
                >
                </el-option>
              </el-select>
            </div>
          </template>
        </l-table>
      </div>
    </div>
  </l-layout>
</template>

<script>
export default {
  data() {
    return {
      radioParam: 2,
      tableForm: {
        isBind: false,
      },
      apiTable: [],
      pageParameters: [],
      formOptions: [],
      forminfo: {},
      columns: [],
      primary: "",
      outData: [],
      pageQueryParams: [],
      pageSaveParams: [],
      objectFormOptions: [],
      tableColumns: [
        { label: "参数名", prop: "name", minWidth: "110" },
        { label: "类型", prop: "type", minWidth: "110" },
        { label: "设置", prop: "setting", minWidth: "110" },
      ],
    };
  },
  computed: {
    mainFormOptions() {
      return this.formOptions.filter((item) => item.table == "root");
    },
    arrFormOptions() {
      return this.formOptions.filter((item) => !item.field);
    },
  },
  methods: {
    getChildFormOptions(data) {
      const formOptions = this.formOptions.filter((item) => item.table == data.parent);
      return formOptions;
    },
    restQueryParams() {
      this.pageParameters = this.$deepClone(this.pageQueryParams);
    },
    restSaveParams() {
      this.outData = this.$deepClone(this.pageSaveParams);
    },
    getOutName(item) {
      switch (item.type) {
        case "basic":
          return "基本";
        case "object":
          return "对象";
        case "array":
          return "数组";
      }
    },
    setFormDesign(data) {
      this.forminfo = data;

      this.formOptions = data.tabList.flatMap((item) =>
        item.components
          .filter((item) => item.table)
          .flatMap((item) => {
            if (item.type == "gridtable") {
              return [
                { label: item.table, value: item.prop, table: item.table },
                ...item.children.map((t) => {
                  return {
                    label: `${t.table}-${t.field}`,
                    value: t.prop,
                    table: t.table,
                    field: t.field,
                  };
                }),
              ];
            } else if (item.table && item.field) {
              return [
                {
                  label: `${item.table}-${item.field}`,
                  value: item.prop,
                  table: item.table,
                  field: item.field,
                },
              ];
            } else {
              return [{ label: item.table, value: item.prop, table: item.table }];
            }
          })
      );
      this.objectFormOptions = [...new Set(this.formOptions.map((item) => item.table))].map((item) => ({
        lable: item,
        value: item,
      }));
    },
    radioParamChange(val) {
      if (val == 1) {
        const apiPost = this.apiTable.find((item) => item.f_RequestMethod == "post");
        let postParameters = apiPost.f_RequestParameters;
        let postParams = JSON.parse(postParameters);
        this.pageSaveParams = this.arrToTree(this.turnPostParams(postParams));
      } else {
        const apiEdit = this.apiTable.find((item) => item.f_RequestMethod == "put");
        let editResponseType = JSON.parse(apiEdit.f_ResponseType);
        this.pageSaveParams = this.arrToTree(this.turnStructParams(editResponseType));
      }
      this.outData = this.pageSaveParams;
    },
    setRadioParam() {
      if (this.radioParam == 1) {
        const apiPost = this.apiTable.find((item) => item.f_RequestMethod == "post");
        let postParameters = apiPost.f_RequestParameters;
        let postParams = JSON.parse(postParameters);
        const pageSaveParams = this.turnPostParams(postParams);
        this.pageSaveParams = this.arrToTree(pageSaveParams);
        return !pageSaveParams.length;
      } else {
        const apiEdit = this.apiTable.find((item) => item.f_RequestMethod == "put");
        let editResponseType = JSON.parse(apiEdit.f_ResponseType);
        const pageSaveParams = this.turnStructParams(editResponseType);
        this.pageSaveParams = this.arrToTree(pageSaveParams);
        return !pageSaveParams.length;
      }
    },
    //接口输出-表单数据
    setFormData(dbTableData, scheme, designDbTables) {
      this.columns = [...new Set(designDbTables.flatMap((item) => item.columns.map((key) => key.name)))];

      this.apiTable = dbTableData || [];
      this.primary = scheme && scheme.primaryKey;
      this.radioParam = (scheme.output && scheme.output.mode) || 1;

      if (this.setRadioParam()) {
        this.outData = this.pageSaveParams;
      } else {
        this.outData =
          scheme.output && scheme.output.apiSave ? this.arrToTree(scheme.output.apiSave) : this.pageSaveParams;
      }
    },
    getPrimary() {
      return this.primary;
    },

    arrToTree(arr, parent = "") {
      let newArr = [];
      arr.forEach((item) => {
        if (item.parent == parent) {
          newArr.push({
            ...item,
            children: this.arrToTree(arr, item.name),
          });
        }
      });
      return newArr;
    },
    //接口输出-提交数据
    getData() {
      return {
        mode: this.radioParam,
        apiSave: this.toArray(this.outData),
      };
    },
    toArray(arr) {
      const result = [];
      const loop = (data) => {
        let child = data.children;
        if (child && child.length) {
          child.forEach((item) => {
            loop(item);
          });
        }

        delete data.children;
        result.push(data);
      };

      arr.forEach((item) => {
        loop(item);
      });
      return result;
    },
    turnPostParams(params, parent = "", arr = []) {
      if (Object.prototype.toString.call(params) == "[object Object]") {
        Object.keys(params).forEach((key) => {
          if (Object.prototype.toString.call(params[key]) == "[object Object]") {
            arr.push({
              id: `${parent}_${key}`,
              name: key,
              type: "object",
              parent: parent,
              value: "",
            });
            this.turnPostParams(params[key], key, arr);
          } else if (Array.isArray(params[key])) {
            arr.push({
              id: `${parent}_${key}`,
              name: key,
              type: "array",
              parent: parent,
              value: "",
            });
            this.turnPostParams(params[key], key, arr);
          } else {
            arr.push({
              id: `${parent}_${key}`,
              name: key,
              type: "basic",
              parent: parent,
              value: "",
            });
          }
        });
      } else if (Array.isArray(params)) {
        if (Object.prototype.toString.call(params[0]) == "[object Object]") {
          this.turnPostParams(params[0], parent, arr);
        }
      } else {
        arr.push({
          id: `${parent}_${params}`,
          name: params,
          type: "basic",
          parent: parent,
          value: "",
        });
      }

      return arr;
    },
    turnStructParams(responseType) {
      let mainDbTables = [];
      let childDbTables = [];
      if (responseType.propertysInfo) {
        const mainData = responseType.propertysInfo.filter((item) => !item.propertysInfo.length);
        if (mainData.length) {
          mainDbTables = mainData.map((item) => {
            return {
              id: `_${item.propertyName.toLowerCase()}`,
              name: item.propertyName.toLowerCase(),
              type: "basic",
              parent: "",
              value: "",
            };
          });
        }
        const childData = responseType.propertysInfo.filter((item) => item.propertysInfo.length);
        if (childData.length) {
          let parentDbTable = childData.map((item) => {
            return {
              id: `_${item.propertyName.toLowerCase()}`,
              name: item.propertyName.toLowerCase(),
              type: item.isArray ? "array" : "object",
              parent: "",
              value: "",
            };
          });
          let childDbTable = childData.flatMap((item) => {
            return item.propertysInfo.map((t) => {
              return {
                id: `${item.propertyName.toLowerCase()}_${t.propertyName.toLowerCase()}`,
                name: t.propertyName.toLowerCase(),
                type: "basic",
                parent: item.propertyName.toLowerCase(),
                value: "",
              };
            });
          });
          childDbTables = parentDbTable.concat(childDbTable);
        }
      }
      return mainDbTables.concat(childDbTables);
    },
  },
};
</script>
